<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动昵称" prop="activityName">
        <el-input
          v-model="queryParams.activityName"
          placeholder="请输入活动昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['projects:SlActivitys:add']"
        >创建活动</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SlActivitysList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动昵称" align="center" prop="activityName" />
      <el-table-column label="开始时间" align="center" prop="activityStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activityStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="activityEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activityEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动封面图" align="center" prop="activityImg" width="100">
        <template slot-scope="scope">
          <!-- 保持原有预览组件，确保表格中图片正常显示 -->
          <image-preview :src="scope.row.activityImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="活动费用" align="center" prop="activityMoney" />
      <el-table-column label="活动原价" align="center" prop="activityOldMoney" />
      <el-table-column label="上架状态" align="center" prop="ifFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_flag" :value="scope.row.ifFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['projects:SlActivitys:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['projects:SlActivitys:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改店内活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动昵称" prop="activityName">
          <el-input v-model="form.activityName" placeholder="请输入活动昵称" />
        </el-form-item>
        <el-form-item label="开始时间" prop="activityStartTime">
          <el-date-picker clearable size="small"
            v-model="form.activityStartTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择活动开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="activityEndTime">
          <el-date-picker clearable size="small"
            v-model="form.activityEndTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择活动结束时间">
          </el-date-picker>
        </el-form-item>
        <!-- 改造核心：替换为el-upload组件 -->
        <el-form-item label="活动封面" prop="activityImg">
          <el-upload 
            ref="activityImgUpload" 
            :file-list="activityImgFileList" 
            :action="uploadUrl" 
            :headers="headers"
            :auto-upload="true" 
            :before-upload="handleBeforeUpload"  
            :on-success="handleUploadSuccess"  
            :on-error="handleUploadError" 
            :on-remove="handleRemove" 
            :limit="1" 
            list-type="picture-card" 
            accept="image/jpeg,image/png,image/jpg"  
            name="file">
            <!-- 上传按钮/加载状态 -->
            <i v-if="!uploadLoading" class="el-icon-plus"></i>
            <el-loading v-else type="spinner" size="small"></el-loading>
            <!-- 上传提示 -->
            <div slot="tip" class="el-upload__tip">支持 JPG/PNG 格式，大小不超过 2MB，仅可上传1张</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动费用" prop="activityMoney">
          <el-input v-model="form.activityMoney" placeholder="请输入活动费用" type="number"/>
        </el-form-item>
        <el-form-item label="活动原价" prop="activityOldMoney">
          <el-input v-model="form.activityOldMoney" placeholder="请输入活动原价" type="number"/>
        </el-form-item>
        <el-form-item label="上架状态">
          <el-radio-group v-model="form.ifFlag">
            <el-radio
              v-for="dict in dict.type.product_flag"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSlActivitys, getSlActivitys, delSlActivitys, addSlActivitys, updateSlActivitys } from "@/api/projects/SlActivitys";
import { getToken } from "@/utils/auth"; // 引入Token工具，用于上传身份验证

export default {
  name: "SlActivitys",
  dicts: ['product_flag'],
  data() {
    return {
      // 新增：图片上传配置
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传接口地址（复用项目通用上传接口）
      headers: { Authorization: "Bearer " + getToken() }, // 上传请求头（携带Token验证）
      uploadLoading: false, // 上传加载状态（避免重复上传）
      activityImgFileList: [], // 活动封面图文件列表（用于el-upload回显）
      // 原有基础数据
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      SlActivitysList: [],
      title: "",
      open: false,
      daterangeActivityStartTime: [],
      daterangeActivityEndTime: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityName: null,
        activityStartTime: null,
        activityEndTime: null,
        ifFlag: null,
      },
      form: {},
      rules: {
        // 新增：活动封面图校验（可选，根据业务需求决定是否必填）
        activityImg: [
          { required: true, message: "请上传活动封面图", trigger: "change" }
        ],
        // 原有表单校验（补充完整）
        activityName: [
          { required: true, message: "请输入活动昵称", trigger: "blur" }
        ],
        activityStartTime: [
          { required: true, message: "请选择活动开始时间", trigger: "change" }
        ],
        activityEndTime: [
          { required: true, message: "请选择活动结束时间", trigger: "change" }
        ],
        activityMoney: [
          { required: true, message: "请输入活动费用", trigger: "blur" },
          
        ],
        activityOldMoney: [
          { required: true, message: "请输入活动原价", trigger: "blur" },
         
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询店内活动列表（原有方法，保持不变） */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeActivityStartTime && '' != this.daterangeActivityStartTime) {
        this.queryParams.params["beginActivityStartTime"] = this.daterangeActivityStartTime[0];
        this.queryParams.params["endActivityStartTime"] = this.daterangeActivityStartTime[1];
      }
      if (null != this.daterangeActivityEndTime && '' != this.daterangeActivityEndTime) {
        this.queryParams.params["beginActivityEndTime"] = this.daterangeActivityEndTime[0];
        this.queryParams.params["endActivityEndTime"] = this.daterangeActivityEndTime[1];
      }
      listSlActivitys(this.queryParams).then(response => {
        this.SlActivitysList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // -------------------------- 新增：图片上传核心方法 --------------------------
    /** 上传前校验（文件大小、格式） */
    handleBeforeUpload(file) {
      // 1. 校验文件大小（≤2MB）
      const isLt2MB = file.size / 1024 / 1024 <= 2;
      if (!isLt2MB) {
        this.$message.error(`当前文件 ${file.name} 大小超过 2MB，请压缩后上传`);
        return false;
      }

      // 2. 校验文件格式（仅支持JPG/PNG）
      const allowTypes = ["image/jpeg", "image/png", "image/jpg"];
      const isImg = allowTypes.includes(file.type);
      if (!isImg) {
        this.$message.error(`当前文件 ${file.name} 格式不支持，请上传 JPG/PNG 图片`);
        return false;
      }

      // 3. 开启上传加载状态
      this.uploadLoading = true;
      return true;
    },

    /** 上传成功处理 */
    handleUploadSuccess(res, file) {
      // 1. 关闭加载状态
      this.uploadLoading = false;

      // 2. 接口返回成功（code=200）才同步数据
      if (res.code === 200) {
        // 清空原有列表（确保仅保留1张封面图）
        this.activityImgFileList = [];
        // 添加新图到回显列表（格式需符合el-upload要求：id、name、url）
        this.activityImgFileList.push({
          id: Date.now(), // 用时间戳做唯一标识，避免重复
          name: file.name, // 文件名（用于显示）
          url: res.url // 接口返回的图片在线URL（用于预览和提交）
        });
        // 同步到表单字段（提交给后端的封面图URL）
        this.form.activityImg = res.url;
        this.$message.success("活动封面图上传成功");
      } else {
        // 上传失败，走统一错误处理
        this.handleUploadError(res, file);
      }
    },

    /** 上传失败处理 */
    handleUploadError(res, file) {
      // 1. 关闭加载状态
      this.uploadLoading = false;

      // 2. 移除错误文件（避免留在列表中）
      this.activityImgFileList = this.activityImgFileList.filter(item => item.url !== file.response?.url);

      // 3. 提示错误信息（优先用接口返回msg，无则用默认文案）
      this.$message.error(res.msg || `文件 ${file.name} 上传失败，请重试`);
    },

    /** 图片删除处理 */
    handleRemove(file, fileList) {
      // 1. 同步回显列表（el-upload自动更新fileList，直接赋值即可）
      this.activityImgFileList = fileList;

      // 2. 同步表单字段（列表为空则清空URL）
      this.form.activityImg = fileList.length > 0 ? fileList[0].url : "";
      this.$message.info("活动封面图已删除");
    },

    // -------------------------- 原有方法改造：新增图片列表初始化 --------------------------
    /** 表单重置（新增：清空图片列表） */
    reset() {
      this.form = {
        id: null,
        activityName: null,
        activityStartTime: null,
        activityEndTime: null,
        activityImg: "", // 重置为空字符串（避免null导致异常）
        activityMoney: null,
        activityOldMoney: null,
        ifFlag: "0",
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
      };
      // 新增：重置图片上传相关状态
      this.activityImgFileList = [];
      this.uploadLoading = false;
      this.resetForm("form");
    },

    /** 修改按钮操作（新增：图片回显） */
    handleUpdate(row) {
      this.reset(); // 先执行重置，清空原有数据
      const id = row.id || this.ids;
      getSlActivitys(id).then(response => {
        this.form = response.data;
        const { activityImg } = this.form;

        // 新增：图片回显（将接口返回的URL转成el-upload需要的列表格式）
        if (activityImg) {
          this.activityImgFileList = [{
            id: Date.now(),
            name: "activity_cover.jpg", // 默认文件名
            url: activityImg // 接口返回的封面图URL
          }];
        } else {
          this.activityImgFileList = [];
        }

        this.open = true;
        this.title = "修改店内活动";
      });
    },

    // -------------------------- 原有方法（保持不变） --------------------------
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeActivityStartTime = [];
      this.daterangeActivityEndTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加店内活动";
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSlActivitys(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSlActivitys(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除店内活动编号为"' + ids + '"的数据项？').then(function() {
        return delSlActivitys(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('projects/SlActivitys/export', {
        ...this.queryParams
      }, `SlActivitys_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>